//
//  YKChatViewController.m
//  WeChat
//
//  Created by 吴高烽 on 2016/11/9.
//  Copyright © 2016年 吴高烽. All rights reserved.
//

#import "YKChatViewController.h"

@interface YKChatViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,NSFetchedResultsControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>{
    NSFetchedResultsController *_resultContr;

}
@property (weak, nonatomic) IBOutlet UITableView *tableView;
/** 用户聊天数据 */
//@property (nonatomic ,strong)NSArray *chats;
@property (weak, nonatomic) IBOutlet UIView *inputView;

/**
 输入框底部约束
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *inputY;

@end
static NSString  *reuseIdentity = @"chatCell" ;
@implementation YKChatViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadChatData];
    [self noticeKeyBoard];
    
}
- (IBAction)imageChooseButtonAction:(UIButton *)sender {
    UIImagePickerController *imagePc =[[UIImagePickerController alloc]init];
    imagePc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePc.delegate = self ;
    [self presentViewController:imagePc animated:YES completion:^{
        
    }];
}
#pragma mark- 用户选择好图片后调用
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    YKLog(@"info==%@",info);
    UIImage *img = info[UIImagePickerControllerOriginalImage];
//    NSData *data = UIImagePNGRepresentation(img);
//    [self sendAttachmentWithData:data bodyType:@"image"];
    [self dismissViewControllerAnimated:YES completion:nil];
}
-(void)sendImage:(UIImage*)img{
//    1. 把文件上传到文件服务器
    /*
     * //!> 文件上传的路径 
     
     */
}
#pragma mark- 发送（图片）附件
-(void)sendAttachmentWithData:(NSData*)data bodyType:(NSString*)type{
    XMPPMessage *msg = [XMPPMessage messageWithType:@"chat" to:self.friendJid];
    [msg addAttributeWithName:@"bodyType" stringValue:type];
#warning 没有body就不认
    [msg addBody:type];
    NSString *baseStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

    XMPPElement *attachment = [XMPPElement elementWithName:@"attachment" stringValue:baseStr];
    [msg addChild:attachment];
    [[YKXMPPTool shareYKXMPPTool].xmppStream sendElement:msg];
    
}
/**
 监听键盘的变化
 */
-(void)noticeKeyBoard{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardHide:) name:UIKeyboardWillHideNotification object:nil];

}
-(void)keyboardShow:(NSNotification*)noti{
    /** UIKeyboardAnimationCurveUserInfoKey = 7;
     UIKeyboardAnimationDurationUserInfoKey = "0.25";
     UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}";
     UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 796}";
     UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 538}";
     UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 258}}";
     UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 409}, {375, 258}}";
     UIKeyboardIsLocalUserInfoKey = 1;
     }*/
    NSDictionary *dict = noti.userInfo ;
//    CGFloat duration = [dict[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    CGFloat height = [dict[UIKeyboardFrameEndUserInfoKey]CGRectValue].size.height;
    self.inputY.constant = height;
//    [UIView animateWithDuration:duration animations:^{
//        self.inputView.transform = CGAffineTransformMakeTranslation(0, height-SCHeight);
//    }];
//    YKLog(@"%@",noti);
}
-(void)keyboardHide:(NSNotification*)noti{
    self.inputY.constant = 0;
}
/**
 加载数据库的聊天数据
 */
-(void)loadChatData{
//    1、 上下文
    NSManagedObjectContext *msgContext = [YKXMPPTool shareYKXMPPTool].msgArchStorge.mainThreadManagedObjectContext;
//    2、查询请求
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"XMPPMessageArchiving_Message_CoreDataObject"];
//    3、过滤（当前登录用户并且好友的聊天消息）
    NSString *loginUserJid = [YKXMPPTool shareYKXMPPTool].xmppStream.myJID.bare;
    NSPredicate *pre = [NSPredicate predicateWithFormat:@"streamBareJidStr = %@ AND bareJidStr = %@",loginUserJid,self.friendJid.bare];
    request.predicate = pre ;
//    4、设置内容时间排序
    NSSortDescriptor *timeSort = [NSSortDescriptor sortDescriptorWithKey:@"timestamp" ascending:YES];
    request.sortDescriptors = @[timeSort];
//    5、 执行请求
    _resultContr =[[NSFetchedResultsController alloc]initWithFetchRequest:request managedObjectContext:msgContext sectionNameKeyPath:nil cacheName:nil];
    _resultContr.delegate = self;
    NSError *error = nil;
    [_resultContr performFetch:&error];
    if (error) {
        YKLog(@"%@",error);
    }else{
        YKLog(@"%@",_resultContr.fetchedObjects);
//        self.chats = _resultContr.fetchedObjects ;
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _resultContr.fetchedObjects.count ;
//    return self.chats.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:reuseIdentity];
    XMPPMessageArchiving_Message_CoreDataObject *msgObj = _resultContr.fetchedObjects[indexPath.row];
    XMPPMessage *message = msgObj.message ;
//    获取附件类型
    NSString* bodyType = [message attributeStringValueForName:@"bodyType"];
    NSLog(@"bodytype = %@",bodyType);
    if ([bodyType isEqualToString:@"image"]) {// 图片数据太大会获取失败
        NSArray *child = message.children ;
        for (XMPPElement *note in child) {
            if ([[note name] isEqualToString:@"attachment"]) {
                YKLog(@"获取到附件");
                NSString *imageBase64Str = [note stringValue];
                NSData *imageData = [[NSData alloc]initWithBase64EncodedString:imageBase64Str options:NSDataBase64DecodingIgnoreUnknownCharacters];
                UIImage *image = [UIImage imageWithData:imageData];
                cell.imageView.image = image ;
                cell.textLabel.text = msgObj.body;

            }
        }
    }else if ([bodyType isEqualToString:@"sound"]){
        
    }else if ([bodyType isEqualToString:@"doc"]){
        
    }else{ // 默认为文本消息
        cell.imageView.image = nil ;
        cell.textLabel.text = msgObj.body;
    }
    return cell;

}
-(void)controllerDidChangeContent:(NSFetchedResultsController *)controller{
    [self.tableView reloadData];
    NSIndexPath *lastIndex = [NSIndexPath indexPathForRow:_resultContr.fetchedObjects.count-1  inSection:0];
    [self.tableView scrollToRowAtIndexPath:lastIndex atScrollPosition:UITableViewScrollPositionBottom animated:YES];
//    [self.us]
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}
#pragma mark- textfieldelegat
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    NSString *txt = textField.text ;
    XMPPMessage *msg = [XMPPMessage messageWithType:@"chat" to:self.friendJid];
    [msg addBody:txt];
    [[YKXMPPTool shareYKXMPPTool].xmppStream sendElement:msg];
    textField.text = nil ;
    return  YES ;
//    return NO;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
